package com.problem.basic;

import java.io.FileWriter;
import java.io.IOException;
import com.util.solution.inter.Solution;

public abstract class Problem<T extends Solution> {
	/**
	 * description of the problem
	 */
	public String problem_des;
	/**
	 * the number of run times
	 */
	protected int run_num;
	/**
	 * the number of objective
	 */
	public int obj_num;
	/**
	 * the number of subproblems
	 */
	public int sub_num;
	/**
	 * used for moead framework
	 */
	public T [] solutionArray;
	
	/**
	 * initialize all parameters
	 */
	public abstract void initialParameters();
	/**
	 * initialize the population
	 * @param pop_size
	 */
	public abstract void initialPopulation(int pop_size);
	
	public void saveResults(String fileName){
		try {
			FileWriter fw = new FileWriter(fileName, false);
			for(Solution s : this.solutionArray){
				if(s.object_val[0]==0 && s.object_val[1]==0) continue;
				for(int i=0;i<s.getObj_num();i++){
					fw.write(String.valueOf(s.object_val[i]));
					fw.write(" ");
				}
				fw.write("\n");
			}
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * find the index
	 * @param s
	 * @param pop_size
	 * @param weights
	 * @return
	 */
	public int getIndex(Solution s, int pop_size, double [] weights) {
		double x1 = 1.0*s.object_val[0]/(s.object_val[0]+s.object_val[1]);
		double x2 = 1.0*s.object_val[1]/(s.object_val[0]+s.object_val[1]);
		double max = Double.MIN_VALUE;
		int index = -1;
		for(int i=0;i<pop_size;i++) {
			double y1 = weights[2*i];
			double y2 = weights[2*i+1];
			double cosVal = (x1*y1+x2*y2)/(Math.sqrt(x1*x1+x2*x2)*Math.sqrt(y1*y1+y2*y2));
			if(cosVal>max) { 
				max = cosVal; 
				index = i;
			}
		}
		return index;
	}
}
